package com.reggie.controller.admin;

import com.reggie.dto.GoodsSalesDTO;
import com.reggie.entity.Orders;
import com.reggie.result.R;
import com.reggie.service.ReportService;
import com.reggie.service.WorkSpaceService;
import com.reggie.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/report")
@Slf4j
@Api(tags = "统计报表的接口")
public class ReportController {
    @Autowired
    private ReportService reportService;
    @Autowired
    private WorkSpaceService workSpaceService;


    /**
     * 统计营业额数据
     *
     * @return
     */
    @GetMapping("/turnoverStatistics")
    @ApiOperation("营业额统计的数据")
    public R<TurnoverReportVO> turnoverStatistics(
            //设置时间格式
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {

        //创建一个空的日期对象数组
        ArrayList<LocalDate> datelist = new ArrayList<>();
        //加入起始时间
        datelist.add(begin);
        while (!begin.equals(end)) {
            //如果当前的时间不等于结束时间
            begin = begin.plusDays(1); //获取当前时间的下一日
            datelist.add(begin); //利用循环 将 循环得到的每一个日期添加到数组
        }


        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : datelist) {
            //获取遍历的第一个时间一天的时间开始时间00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //获取遍历的第一个时间一天的时间结束时间23:59
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询日期区间营业额
            Double turnover = reportService.getTurnover(beginTime, endTime);
            //将每日的营业额传入数组内
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                //StringUtils.join 可以将数组拆分成字符串并用,隔开
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return R.success(turnoverReportVO);

    }


    @GetMapping("/userStatistics")
    @ApiOperation("新增用户数据统计")
    public R<UserReportVO> userStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        ArrayList<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        //将选定时间段的日期装到时间对象数组
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : datelist) {
            //获取当天的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //获取当天新用户的数量
            Integer newUser = reportService.getUserCount(beginTime, endTime);
            //获取截止至今所有的用户数量
            Integer totalUser = reportService.getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);

        }
        return R.success(UserReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build());
    }


    @GetMapping("/ordersStatistics")
    @ApiOperation("用户数据统计")
    public R<OrderReportVO> orderStatistics(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数
            Integer OrderCount = reportService.getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单
            Integer vaildOrderCount = reportService.getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(OrderCount);
            validOrderCountList.add(vaildOrderCount);
        }
        //时间区间的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间的有效订单
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单的完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return R.success(orderReportVO);


    }


    @GetMapping("/top10")
    @ApiOperation("销量排名")
    public R<SalesTop10ReportVO> top10(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //获取菜品名称以及对应的数量 封装对象存入数组
        List<GoodsSalesDTO> goodsSalesDTOList = reportService.getSalesTop10(beginTime, endTime);
        //  获取数组内  每个菜品名称
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        //  获取数组内  每个菜品的数量
        //.stream 将集合转换为 流    .map(GoodsSalesDTO::getNumber)将集合对象 遍历并取出里面的number属性  .collect(Collectors.toList() 将遍历的属性值收集转换成数组
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
        return R.success(top10ReportVO);
    }


    @GetMapping("/export")
    @ApiOperation("导出Excel运营报表")
    public void exportXLSX(HttpServletResponse response) {

        //设置开始时间为当前时间的前30天
        LocalDate begin = LocalDate.now().plusDays(-30);
        //设置结束时间是当前时间的前一日
        LocalDate end = LocalDate.now().plusDays(-1);

        //查询概览 运营数据 提供给Excel模板文件
        BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //.getClass() 获取当前类 .getClassLoader()返回类的类加载器  .getResourceAsStream  获取指定路径下的文件输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //获取提前设置好的表格
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获取表格中的sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //设置第二行第一格的值
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);

            //获取第四行
            XSSFRow row = sheet.getRow(3);
            //第四行第二格 设置营业额值
            row.getCell(2).setCellValue(businessData.getTurnover());
            //第四行第四格 设置订单完成率的值
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //第四行第六格 设置新增用户值
            row.getCell(6).setCellValue(businessData.getNewUsers());


            //获取第五行
            row = sheet.getRow(4);
            //第五行第二格 设置有效订单的值
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            //第五行第四格 设置平均客单价的值
            row.getCell(4).setCellValue(businessData.getUnitPrice());


            for (int i = 0; i < 30; i++) {
                //设置循环加1
                LocalDate date = begin.plusDays(i);
                //准备当日明细数据
                businessData = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获取第七行
                row = sheet.getRow(7 + i);
                //第七行第一格 设置日期 ,将日期格式转换拿为字符串
                row.getCell(1).setCellValue(date.toString());
                //设置营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流 将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            //关闭资源
            out.flush();
            out.close();
            excel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}








